# 回测
import asyncio
import queue
import random
import sys
import threading
import time

import pandas as pd
from config.config import *

from data.datahandle import dataHandle
from data.handle_pytdx import handlePytdx
from trade.trade_handle import TraderHandle

class LogicTest:
    def __init__(self, strategy, args):
        self.strategy = strategy
        self.args = args

    def event_loop(self, data):
        event = pd.DataFrame(data[:1])
        for i in range(1, len(data)):
            event = pd.concat([event, data[i:i+1]])
            # event.push_data(data[i:i+1])
            self.strategy.on_bars(event)
        return event

    async def backtest(self, queue_object, stock_code):
        if(ONLINE_SOURCE_TYPE == 'pytdx'):
            handle = handlePytdx()
        data_handle = dataHandle(handle, stock_code)
        data = data_handle.get_data()

        event = self.event_loop(data)
        
        # data = ('BTC BUY - Binance price: ' + str(random.uniform(0.1, 983585837738573.568))) if random.uniform(0.1, .9) > .5 else 'BTC SELL - Binance price: ' + str(random.uniform(0.1,983585837738573.568))
        payload = {'ts' : time.time() , 'data' : event[-1:], 'stock_code' : stock_code}
        queue_object.put(payload)

        # return event

    async def async_handler(self, queue_object):
        loop = asyncio.get_event_loop()
        if BACKTEST_STOCK_LIST is None:
            print("请设置回测的股票列表")

        tasks = []
        for stock_code in BACKTEST_STOCK_LIST:
            tasks.append(self.backtest(queue_object, stock_code))
     
        await asyncio.gather(*tasks)
        
    def gen_signal(self, queue_object):
        asyncio.run(self.async_handler(queue_object))

    def run(self):
        # Create a queue
        queue_object = queue.Queue()

        # Create and start the reader thread
        trade_handle = TraderHandle()
        # Create and start the reader thread
        trade = threading.Thread(target=trade_handle.run, args=(queue_object,))
        trade.start()

        # Create and start the writer thread
        signal = threading.Thread(target=self.gen_signal, args=(queue_object,))
        signal.start()

        # while True:
        #     if not trade.is_alive():
        #         print("Reader thread has terminated unexpectedly.")
        #         # Take appropriate action like logging, restarting the thread, or stopping the program
        #     else:
        #         print('reader is alive')

        #     if not signal.is_alive():
        #         print("Writer thread has terminated unexpectedly.")
        #         # Take appropriate action like logging, restarting the thread, or stopping the program
        #     else:
        #         print('write is alive')
        #     # Sleep for some time before checking the thread status again
        #     time.sleep(1)

        # Wait for both threads to finish
        trade.join()
        signal.join()